﻿using Newtonsoft.Json.Linq;
using Qianke.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace MainFrame.Plugs
{
    public static class SystemController
    {
        /// <summary>
        /// 获取 插件 版本
        /// </summary>
        /// <returns></returns>
        public static async Task<ReturnInfo> GetVersion(JObject obj)
        {
            await Task.Delay(0);
            return new ReturnInfoData("2.0");
        }


 

        /// <summary>
        /// 更新登录信息
        /// </summary>
        /// <returns></returns>
        public static async Task<ReturnInfo> UpdateManager(JObject obj)
        {
            await Task.Delay(0);
            return ReturnInfo.Success;
            //return EquipmentApi.UpdateManager(MainForm.Token, obj["ManagerId"].ToInt64(0), obj["OrganId"].ToInt64(0));
        }


        /// <summary>
        /// 写本地文件
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static async Task<ReturnInfo> WriteFile(JObject obj)
        {
            var filePath = obj["FilePath"].SafeToString();
            var writeContext = obj["WriteContext"].SafeToString();
            var bAppend = obj["Append"].ToInt(0);
            var strEncoding = obj["Encoding"].SafeToString("utf-8");
            var encoding = Encoding.GetEncoding(strEncoding);

            var fileDir = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(fileDir))
                Directory.CreateDirectory(fileDir);

            FileMode fileModel = FileMode.OpenOrCreate;
            if (bAppend == 1)
                fileModel |= FileMode.Append;
            else
                fileModel |= FileMode.Truncate;
            using (var fs = new FileStream(filePath, fileModel, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                var buffer = encoding.GetBytes(writeContext);
                await fs.WriteAsync(buffer, 0, buffer.Length);
            }
            return ReturnInfo.Success;
        }

        public static async Task<ReturnInfo> PostFileToFtp(JObject obj)
        {
            var fileContent = obj["FileContent"].SafeToString();
            var remoteFile = obj["RemoteFile"].SafeToString();
            var userName = obj["FtpUserName"].SafeToString();
            var passWord = obj["FtpPassWord"].SafeToString();
            var ftpAddress = obj["FtpAddress"].SafeToString();
            var strEncoding = obj["Encoding"].SafeToString("utf-8");

            var ftp = (FtpWebRequest)WebRequest.Create($"ftp://{ftpAddress}/" + remoteFile);
            ftp.Credentials = new NetworkCredential(userName, passWord);
            ftp.UseBinary = true;
            ftp.UsePassive = true;
            ftp.KeepAlive = false;
            ftp.Method = WebRequestMethods.Ftp.UploadFile;
            using (var ftpStream = ftp.GetRequestStream())
            {
                var buffer = Encoding.GetEncoding(strEncoding).GetBytes(fileContent);
                await ftpStream.WriteAsync(buffer, 0, buffer.Length);
                ftp = null;
            }
            return ReturnInfo.Success;
        }

        public static async Task<ReturnInfo> ReadFile(JObject obj)
        {
            var filePath = obj["FilePath"].SafeToString();
            if (File.Exists(filePath))
            {
                using(var ms = new MemoryStream())
                {
                    using (var ftpStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        var buffer = new byte[1024];
                        var nSize = 0;
                        while((nSize = await ftpStream.ReadAsync(buffer,0,1024))>0)
                            await ms.WriteAsync(buffer, 0, nSize);
                        return new ReturnInfoData(Convert.ToBase64String(ms.ToArray()));
                    }
                }
            }
            return new ReturnInfo("01", "文件不存在");
        }

    }
}
